package com.sugon.thread;

import org.junit.Test;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 普通线程可能阻塞，比如cpu分配时间到期
 * ForkJoin分配任务根据电脑cpu核数，分配线程任务
 * @author LUOYUAN
 * @create 2018-12-07-22:29
 */
public class TestForkjoin {

    /**
     * ForkJoin框架
     */
    @Test
    public void test1(){
        Instant start = Instant.now();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 10000000000L);
        long sum = pool.invoke(task);
        System.out.println(sum);
        Instant end = Instant.now();

        System.out.println("耗费的时间为: " + Duration.between(start,end).toMillis()); //2768
    }

    @Test
    public void test2(){
        long start = System.currentTimeMillis();

        long sum = 0L;

        for (long i = 0L; i <= 10000000000L; i++) {
            sum += i;
        }

        System.out.println(sum);

        long end = System.currentTimeMillis();

        System.out.println("耗费的时间为: " + (end - start)); //3051
    }

    /**
     * 并行流的提升,内部使用ForkJoin框架，多线程处理数据
     */
    @Test
    public void test3(){
        long start = System.currentTimeMillis();
        //long reduce = LongStream.rangeClosed(0L, 10000000000L).reduce(0, Long::sum);
        Long sum = LongStream.rangeClosed(0L, 10000000000L)
                .parallel() //并行流
                .sum();
        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println("耗费的时间为: " + (end - start)); //1410
    }

    @Test
    public void string(){
        String str="888";
        //把str类型转化为BigDecimal
        BigDecimal bd=new BigDecimal(str);

        //判断是否大于0
        if(bd.compareTo(BigDecimal.ZERO)>0){
            System.out.println(str);
        }else {
            System.out.println("小于0");
        }
    }

}
